package peace.util {
public class Xmls {
    /**
     * @param list
     * @param nodeWrapperClassOrClosure function (node:XML):*{} or Class(node:XML)
     * @return
     */
    public static function map(list:XMLList, nodeWrapperClassOrClosure:*):Array {
        var node:XML, array:Array = [];
        for each (node in list) {
            array.push(nodeWrapperClassOrClosure is Function
                    ? nodeWrapperClassOrClosure(node) : new nodeWrapperClassOrClosure(node))
        }
        return array;
    }

    /**
     *
     * @param xml
     * @return
     */
    public static function xml2object(xml:XML):Object {

        var parse:Function = function(node:XML):Object {
            var attributes:XMLList = node.attributes();
            var children:XMLList = node.*;
            var data:Object = {};
            var child:XML, name:String;
            for each (child in attributes) {
                name = child.name();
                data[name] = child.valueOf();
            }
            var names:Object = {};
            for each (child in children) {
                if (child.nodeKind() != 'element') continue;
                name = child.name();
                if (names[name]) names[name].push(child);
                else names[name] = [child];
            }
            var ary:Array;
            for (name in names) {
                ary = names[name];
                if (ary.length > 1) {
                    data[name] = [];
                    for each (child in ary) {
                        data[name].push(parse(child));
                    }
                } else {
                    data[name] = parse(ary[0]);
                }
            }
            return data;
        };

        var o:Object = null;
        if (xml) {
            o = {};
            var name:String = xml.name();
            o[name] = parse(xml);
        }
        return o;
    }
}
}
